package com.m1905.lib.download.util;


import android.app.Application;
import android.content.Context;
import android.content.ContextWrapper;
import android.text.TextUtils;


import com.m1905.lib.download.listener.OnGenerateFilePathListener;
import com.m1905.lib.download.model.DownloadDBItem;
import com.m1905.lib.download.request.RequestFactory;
import com.m1905.lib.download.request.http.HttpUrlConnectionRequestFactory;
import com.m1905.lib.download.task.Interceptor;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author wanghao
 * @date 2023/10/11.
 * @des
 */
public class DownloadPreferences {

    private static RequestFactory mFactory = new HttpUrlConnectionRequestFactory();

    public static void setRequestFactory(RequestFactory factory) {
        if (factory != null) {
            mFactory = factory;
        }
    }

    public static RequestFactory getRequestFactory() {
        return mFactory;
    }

    private static final ExecutorService defExecutor = new ThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

    private static Map<Integer, ExecutorService> mExecutors = new HashMap<>();

    public static ExecutorService getExecutor(int type) {
        ExecutorService executor = mExecutors.get(type);
        return executor != null ? executor : defExecutor;
    }

    public static void setExecutor(int type, ExecutorService executor) {
        mExecutors.put(type, executor);
    }

    private static final Map<Integer, List<Interceptor>> mInterceptorMap = new HashMap<>();

    public static synchronized void addTaskInterceptor(int type, Interceptor interceptor) {
        if (interceptor == null) return;
        List<Interceptor> list = mInterceptorMap.get(type);
        if (list == null) {
            list = new ArrayList<>();
            list.add(interceptor);
            mInterceptorMap.put(type, list);
        } else {
            list.add(interceptor);
        }
    }

    public static List<Interceptor> getTaskInterceptor(int type) {
        return mInterceptorMap.get(type);
    }

    private static Context mAppContext = null;

    public static Context getAppContext() {
        if (mAppContext != null) {
            return mAppContext;
        }
        throw new RuntimeException("please call the DownloadPreferences.init() method first");
    }

    private static OnGenerateFilePathListener pathListener;

    public static void init(Context context) {
        init(context, null);
    }

    public static void init(Context context, OnGenerateFilePathListener listener) {
        if (context instanceof Application) {
            mAppContext = context;
        } else if (context instanceof ContextWrapper) {
            mAppContext = context.getApplicationContext();
        }
        if (listener != null) {
            pathListener = listener;
        }
    }


    public static OnGenerateFilePathListener getGeneratePathListener() {
        if (pathListener == null) {
            pathListener = new DefaultGenerateFilePathListener();
        }
        return pathListener;
    }


    private static class DefaultGenerateFilePathListener implements OnGenerateFilePathListener {

        private File dir = null;

        @Override
        public String onGenerateFilePath(Context context, DownloadDBItem item) {
            if (dir == null) {
                File download = context.getExternalFilesDir("download");
                if (download != null) {
                    dir = new File(download, "1905");
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                }
            }
            if (dir != null) {
                String contentId = !TextUtils.isEmpty(item.getContentId()) ? "_" + item.getContentId() : "";
                String episodeId = !TextUtils.isEmpty(item.getEpisodeId()) ? "_" + item.getEpisodeId() : "";
                String episode = !TextUtils.isEmpty(item.getEpisode()) ? "_" + item.getEpisode() : "";
                String fileName = item.getTitle() + contentId + episodeId + episode;
                File file = new File(dir, fileName);
                if (item.isAutoRename()) {
                    int count = 1;
                    while (file.exists()) {
                        file = new File(dir, fileName + count++);
                    }
                } else {
                    if (file.exists()) {
                        file.delete();
                    }
                }
                return file.getAbsolutePath();
            }
            return null;
        }
    }


}
